<template>
<div class="roles">
  <!-- 面包屑 -->
  <el-breadcrumb class="nav">
    <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 公共内容区域 -->
  <div class="page_content">
    <div class="search">
      <el-input
        v-model="keyWord"
        placeholder="请输入名字进行查找"
        class="input-with-select"
        @keyup.enter="searchList"
      >
        <template #append>
        <el-button @click='searchList'><el-icon><Search /></el-icon></el-button>
        </template>
      </el-input>
      <el-button class="add" type="primary" @click='addUser'>添加用户</el-button>
    </div>
    <!-- 搜索结果显示 -->
    <div class="form" v-show="isSearchForm">
      <el-table :data="searchData" ref="sortTable" :height="sortTableHeight" border style="width: 100%">
        <el-table-column prop="id" label="" width="60" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="250" />
        <el-table-column prop="phone" label="电话" width="180" />
        <el-table-column prop="status" label="身份" width="120" />
        <el-table-column prop="state" label="状态" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.state"/>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template #default="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button class="button" color="#626aef" :dark="isDark" plain @click="revert">返回</el-button>
    </div>
    <div class="form" v-show="isForm">
      <el-table ref="sortTable" :height="sortTableHeight" :data="userList" border style="width: 100%">
        <el-table-column prop="id" label="" width="60" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="250" />
        <el-table-column prop="phone" label="电话" width="180" />
        <el-table-column prop="status" label="身份" width="120" />
        <el-table-column prop="state" label="状态" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.state"/>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template #default="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
     <!-- 底部分页 -->
    <el-pagination class="pagination"
      v-show="isForm"
      background
      layout="prev, pager, next,jumper, ->"
      :total='total'
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      style="text-align: center">
    </el-pagination>
  </div>
  <!-- 弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="添加用户">
    <!-- 添加表单 -->
    <el-form
    ref = "userForm"
     :model="formData" :rules = 'rules'>
      <el-form-item label="用户名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email"> 
        <el-input v-model="formData.email" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="身份" prop="status">
        <el-input v-model="formData.status" placeholder="请输入身份（超级管理员/管理员）"/>
      </el-form-item>
    </el-form>
    <el-alert v-show="isNext" title="请按要求填写完整" type="warning" center show-icon />
    <template #footer>
      <div class="footer_button flex">
        <el-button type="primary" @click="addList(userForm)">确定</el-button>
        <el-button type="danger" @click="cancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
<!-- 弹窗 -->
  <el-dialog v-model="dialogFormVisible1" title="编辑用户">
    <!-- 编辑表单 -->
    <el-form
    ref = "editForm"
     :model="editList" :rules = 'rules1'>
      <el-form-item label="用户名称" prop="name">
        <el-input v-model="editList.name" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email"> 
        <el-input v-model="editList.email" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="editList.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="身份" prop="status">
        <el-input v-model="editList.status" placeholder="请输入身份（超级管理员/管理员）"/>
      </el-form-item>
    </el-form>
    <el-alert v-show="isEdit" title="请按要求填写完整" type="warning" center show-icon />
    <template #footer>
      <div class="footer_button flex">
        <el-button type="primary" @click="changeEdit(editForm)">确定</el-button>
        <el-button type="danger" @click="cancelEdit(editForm)">取消</el-button>
      </div>
    </template>
  </el-dialog>
</div>
</template>

<script>
import { reactive, toRefs, onUpdated, onMounted, ref} from 'vue'
import axios from 'axios'


export default {
  setup(){
    const data = reactive({
      value1: ref(true),
      value2: ref(true),
      keyWord:'',
      dialogFormVisible: false,
      dialogFormVisible1:false,
      isClosable: false,
      isForm: true,
      isSearchForm: false,
      currentPage: 1, //当前页 刷新后默认显示第一页
      pageSize: 10, //每一页显示的数据量 此处每页显示6条数据
      total : '',
      isNext: false,
      isEdit: false,
      searchData:[],
      searchList:[],
      formData:{
          name: '',
          email:'',
          phone:'',
          id:''
      },
      rules:{
        name:[
          {required:true,message:'此项为必填',trigger:'blur'}
        ],
        email:[
          {required:false,
          pattern:/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
          message:'请填写正确邮箱',trigger:'blur'}
          ],
        phone:[
          {required:false,
          pattern:/^[1][3,4,5,7,8][0-9]{9}$/,
          message:'请填写正确手机号',trigger:'blur'}
        ],
        id:[
          {required:true,message:'此项为必填',trigger:'blur'}
        ]
      },
      rules1: {
        name:[
          {required:true,message:'此项为必填',trigger:'blur'}
        ],
        email:[
          {required:false,
          pattern:/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
          message:'请填写正确邮箱',trigger:'blur'}
          ],
        phone:[
          {required:false,
          pattern:/^[1][3,4,5,7,8][0-9]{9}$/,
          message:'请填写正确手机号',trigger:'blur'}
        ],
        id:[
          {required:true,message:'此项为必填',trigger:'blur'}
        ]
      },
      userList:[], 
      userLists:[],  // 用户列表数据
      editList:{},
      Data:{}
    })
    /*表格自适应高度*/
    function getTableHeight(){
      this.$nextTick(function () {
        let exceptHeight = 380;
        // this.$refs.table.$el.offsetTop：表格距离浏览器的高度
        if(sortTable){
          this.sortTableHeight = window.innerHeight - this.$refs.sortTable.$el.offsetTop - exceptHeight;
        }

        // 监听窗口大小变化
        window.onresize = function() {
          if(sortTable){
            data.sortTableHeight = window.innerHeight - self.$refs.sortTable.$el.offsetTop - exceptHeight;
          }
        }
      });
    }
    const changeState=()=>{
      if(data.userList.state == true){
        data.value1 = ref(false)
        data.value2 = ref(false)
      }
    }
    // 查
    const searchList=()=>{
      data.searchList = []
      data.searchData = []
      for( let i=0; i<data.userLists.length; i++) {
        if(data.keyWord == data.userLists[i].name){
          data.searchList.push(data.userLists[i])
        }
      }
      for(let i=0; i<data.searchList.length; i++){
        const newSearchList={
          id: i+1,
          identity: data.searchList[i].identity,
          title: data.searchList[i].id,
          name: data.searchList[i].name,
          email:data.searchList[i].email,
          phone: data.searchList[i].phone,
          state: data.searchList[i].state,
          status:data.searchList[i].status,
        }
        data.searchData.push(newSearchList)
      }
      data.isSearchForm = true
      data.isForm = false
    }
    const revert=()=>{
      data.isForm = true
      data.isSearchForm = false
      data.keyWord = ''
    }
    const addUser=()=>{
      data.dialogFormVisible = true
    }
    const userForm = ref()
    const editForm =ref()
    const sortTable = ref()
    // 增
    const addList=(userForm)=>{
      userForm.validate(res=>{
        if(!res){      //表单验证不通过，什么都不做
          data.isNext = true
          return data.isNext
        }
        //表单验证通过
        data.userLists.push(data.formData)
        data.userList = data.userLists.slice((data.currentPage - 1) * data.pageSize, data.currentPage * data.pageSize)
        data.dialogFormVisible = false
        data.total = data.userLists.length
        data.formData = {}
      })
    }
    //改
    const edit=(Data)=>{
      data.Data = Data
      data.dialogFormVisible1 = true
    }
    const changeEdit=(editForm)=>{
      editForm.validate(res=>{
        if(!res){
          data.isEdit = true
          return data.isEdit
        }else{
      data.userLists[data.Data.id-1] = data.editList
      data.userList = data.userLists.slice((data.currentPage - 1) * data.pageSize, data.currentPage * data.pageSize)
      data.dialogFormVisible1 = false
        }
      })
    } 
    const cancelEdit=(editData)=>{
      data.editList = editData
      data.dialogFormVisible1 = false
    }
    // 删
    const remove=(row)=>{
        // userLists 删除
        data.userLists.forEach((item,index)=>{
            if(item.identity == row.identity && item.email == row.email){
                data.userLists.splice(index, 1)
            }
        })
        for (let i=0;i<data.userLists.length;i++) {
        data.userLists[i].id = i+1
        }
        data.userList = data.userLists.slice((data.currentPage - 1) * data.pageSize, data.currentPage * data.pageSize)
        data.total = data.userLists.length
        //searchList 删除
        data.searchData.forEach((item,index)=>{
            if(item.name == row.name && item.identity == row.identity && item.email == row.email){
                data.searchData.splice(index, 1)
            }
        })    
        for (let i=0;i<data.userLists.length;i++) {
        data.userLists[i].id = i+1
        }
        for( let i=0; i< data.searchData.length; i++) {
            data.searchData[i].order = i+1
        }
        data.total = data.userLists.length
        data.userList = data.userLists.slice((data.currentPage - 1) * data.pageSize, data.currentPage * data.pageSize)
    }
    const cancel=()=>{
      data.formData = {}
      data.dialogFormVisible = false
    }
    onMounted(()=>{
      axios.get('/user/userinfo').then(res=>{
        data.userLists = res.data.users
        for (let i=0;i<data.userLists.length;i++) {
          data.userLists[i].id = i+1
        }
        data.userList = data.userLists.slice(0, 10)
        data.total = data.userLists.length
      }).catch(err=>{
        console.log(err)
      })
    })
    onUpdated(() => {
      for (let i=0; i<data.userLists.length; i++) {
        data.userLists[i].id = i+1
      }
    })
    const handleCurrentChange = (currentPage) => {
      data.currentPage = currentPage; 
      data.userList = data.userLists.slice((data.currentPage - 1) * data.pageSize, data.currentPage * data.pageSize)
    }
    // 用户列表
    const userLists=()=>{
    axios.get('/user/userinfo').then(res=>{
      data.userLists = res.data.users
    }).catch(err=>{
      console.log(err)
    })
    }

    return{
      ...toRefs(data),
      searchList,
      revert,
      addUser,
      addList,
      cancel,
      changeState,
      remove,
      edit,
      userForm,
      editForm,
      sortTable,
      handleCurrentChange,
      changeEdit,
      cancelEdit,
       getTableHeight
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table {
  font-size: 0.1px;
}
::v-deep .el-input {
    width: 50%;
  }
::v-deep .el-button {
  font-size: 10px;
}
::v-deep .pagination {
  margin-top: 30px;
  margin-left: 25%;
}
::v-deep .el-pager li {
  margin: 0 15px;
}
.nav {
  margin-top:10px;
}
.page_content {
  .search {
    width: 80%;
    height: 40px;
    display: flex;
    align-content: center;
    .el-input {    
      width: 400px;
      height: 40px;
    }
    .add {
      margin-left: 20px;
      width: 100px;
      height: 40px;
    }
  }
  .form {
    width:100%;
    margin-top: 40px;
    .button {
      font-size: 10px;
      margin-top: 30px;
      margin-left: 55%;
    }
  }
  .el-dialog {
    .el-form {
      .el-form-item {
        margin-top: 20px;
        display: flex;
        .el-input {
          width: 20px;
          margin-bottom:20px;  
        }
      }
    }
    
  }
}
</style>